package com.dmooo.ymx.fragments;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.dmooo.ymx.R;
import com.dmooo.ymx.activity.PddAdActivity;
import com.dmooo.ymx.activity.PddDetailsActivity;
import com.dmooo.ymx.activity.PddTheamActivity;
import com.dmooo.ymx.activity.PddYunYingActivity;
import com.dmooo.ymx.activity.WebViewActivity;
import com.dmooo.ymx.adapter.PddRecyclerAdapter;
import com.dmooo.ymx.base.BaseLazyFragment;
import com.dmooo.ymx.bean.BannerBean;
import com.dmooo.ymx.bean.PDDBean;
import com.dmooo.ymx.bean.PddClient;
import com.dmooo.ymx.bean.Response;
import com.dmooo.ymx.common.SPUtils;
import com.dmooo.ymx.config.Constants;
import com.dmooo.ymx.https.HttpUtils;
import com.dmooo.ymx.https.onOKJsonHttpResponseHandler;
import com.dmooo.ymx.utils.DrawableCenterTextView;
import com.dmooo.ymx.utils.UIUtils;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cz.msebera.android.httpclient.Header;

/**
 * @属性:拼多多商品页
 * @开发者:wmm
 * @时间:2018/11/21 17:36
 */
public class PddFragment extends BaseLazyFragment{


    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    Unbinder unbinder;


    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.right_icon)
    ImageView rightIcon;
    private PddRecyclerAdapter shopRecyclerAdapter;
    private String pid;

    List<PDDBean> taobaoGuesChildtBeans = new ArrayList<>();
    private int indexNum = 1;
    private String name;
    private String sort;
    private LinearLayoutManager linearLayoutManager;
    private boolean hasdata=true;
    private String sort_gz="0";
    Gson gson=new Gson();
    DecimalFormat df=new DecimalFormat("0.00");
    private TextView[] textViews;
    @BindView(R.id.jiage_st)
    DrawableCenterTextView jiageSt;
    @BindView(R.id.xiaoliang_st)
    DrawableCenterTextView xiaoliangSt;
    @BindView(R.id.yongjin_st)
    DrawableCenterTextView yongjinSt;
    @BindView(R.id.tuiguang_st)
    DrawableCenterTextView tuiguangSt;
    MZBannerView img_banner;
    private List<BannerBean> images3 = new ArrayList<>();
    View view;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
         view = inflater.inflate(R.layout.fragment_pdd_new, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        addListener();
        return view;
    }

    private void init() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            pid = arguments.getString("pid");
            name = arguments.getString("name");
            sort = arguments.getString("sort");
            if("0".equals(arguments.getString("index"))){
                view.findViewById(R.id.ll_root1).setVisibility(View.VISIBLE);
                img_banner=view.findViewById(R.id.img_banner);
                getHomeADimg();
                img_banner.setBannerPageClickListener(new MZBannerView.BannerPageClickListener() {
                    @Override
                    public void onPageClick(View view, int i) {
                        Bundle bundle=new Bundle();
                        bundle.putString("id",images3.get(i).getId());
                        bundle.putString("name",images3.get(i).name);
                        openActivity(PddTheamActivity.class,bundle);
                    }
                });
                view.findViewById(R.id.go_p_four).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle=new Bundle();
                        bundle.putString("channel_type","1");
                        bundle.putString("keyword","今日爆款");
                        openActivity(PddYunYingActivity.class,bundle);
                    }
                });
                view.findViewById(R.id.go_p_five).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle=new Bundle();
                        bundle.putString("channel_type","0");
                        bundle.putString("keyword","1.9包邮");
                        openActivity(PddYunYingActivity.class,bundle);
                    }
                });
                view.findViewById(R.id.go_p_six).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle=new Bundle();
                        bundle.putString("channel_type","2");
                        bundle.putString("keyword","品牌清仓");
                        openActivity(PddYunYingActivity.class,bundle);
                    }
                });
                view.findViewById(R.id.ll_chaneel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        get(4);
                    }
                });
                view.findViewById(R.id.pdd_list_left).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle=new Bundle();
                        bundle.putString("id","1");
                        bundle.putString("name","实时热销榜");
                        bundle.putString("type","1");
                        openActivity(PddTheamActivity.class,bundle);
                    }
                });
                view.findViewById(R.id.pdd_list_right).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle=new Bundle();
                        bundle.putString("id","2");
                        bundle.putString("name","实时收益榜");
                        bundle.putString("type","1");
                        openActivity(PddTheamActivity.class,bundle);
                    }
                });
                view.findViewById(R.id.pdd_card_a).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        get(2);
                    }
                });
                view.findViewById(R.id.pdd_card_b).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        get(7);
                    }
                });
                view.findViewById(R.id.pdd_card_c).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        get(-1);
                    }
                });
                view.findViewById(R.id.pdd_card_d).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        get(0);
                    }
                });
                view.findViewById(R.id.pdd_card_e).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        get(3);
                    }
                });
                view.findViewById(R.id.pdd_card_f).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        get(5);
                    }
                });
                view.findViewById(R.id.pdd_channel_a).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        get2("39998");
                    }
                });
                view.findViewById(R.id.pdd_channel_d).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        get2("39999");
                    }
                });
                view.findViewById(R.id.pdd_channel_b).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        get2("39996");
                    }
                });
                view.findViewById(R.id.pdd_channel_c).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        get2("39997");
                    }
                });
            }
        }
        tuiguangSt.setVisibility(View.GONE);
        yongjinSt.setText("奖");
        textViews = new TextView[]{jiageSt, xiaoliangSt, yongjinSt};
        shopRecyclerAdapter = new PddRecyclerAdapter(getActivity(), R.layout.pdd_item2, taobaoGuesChildtBeans);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(new GridLayoutManager(context,2));
        recyclerView.setAdapter(shopRecyclerAdapter);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int screenMeasuredHeight = UIUtils.getScreenMeasuredHeight(getActivity());
                if (getScollYDistance() >= (screenMeasuredHeight / 2)) {
                    rightIcon.setVisibility(View.VISIBLE);
                } else {
                    rightIcon.setVisibility(View.GONE);
                }
            }
        });
    }
    private void getHomeADimg() {
        RequestParams requestParams = new RequestParams();
        HttpUtils.post(Constants.APP_IP+"/app.php?c=Pdd&a=getThemeList", requestParams, new onOKJsonHttpResponseHandler<BannerBean>(new TypeToken<Response<BannerBean>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//                showToast(throwable.getMessage());
            }

            @Override
            public void onSuccess(int statusCode, Response<BannerBean> datas) {
                if (datas.isSuccess()) {
                    images3.clear();
                    images3.addAll(datas.getData().theme_list);
                    List<String> strings = new ArrayList<>();
                    for (int i = 0; i < images3.size(); i++) {
                        strings.add(images3.get(i).image_url);
                    }
                    if (images3.size() <= 0) {
                        img_banner.setVisibility(View.GONE);
                    } else {
                        img_banner.setVisibility(View.VISIBLE);
                        img_banner.setPages(strings, new MZHolderCreator<BannerViewHolder>() {
                            @Override
                            public BannerViewHolder createViewHolder() {
                                return new BannerViewHolder();
                            }
                        });
                        img_banner.start();
                    }
                } else {
                    showToast(datas.getMsg());
                }
            }
        });
    }
    class BannerViewHolder implements MZViewHolder<String> {
        private ImageView mImageView;

        @Override
        public View createView(Context context) {
            View view = LayoutInflater.from(context).inflate(R.layout.img_t, null);
            mImageView = view.findViewById(R.id.img);
            return view;
        }

        @Override
        public void onBind(Context context, int position, final String data) {
            Glide.with(context).load(data).into(mImageView);
        }
    }
    private void get(int type){
        RequestParams requestParams = new RequestParams();
        requestParams.put("channel_type",type);
        HttpUtils.post(Constants.APP_IP+"/app.php?c=Pdd&a=genRpPromUrl", requestParams, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("dsafsd",responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("dsafsd",responseString);
                try {
                    JSONObject jsonObject=new JSONObject(responseString);
                    if("0".equals(jsonObject.getString("code"))){
                        if(type==-1){
                            Bundle bundle=new Bundle();
                            bundle.putString("urls",jsonObject.getJSONObject("data").getJSONObject("rp_promotion_url_generate_response").getJSONArray("resource_list").toString());
                            openActivity(PddAdActivity.class,bundle);
                            return;
                        }
                        Intent intent = new Intent(context, WebViewActivity.class);
                        intent.putExtra("title", "详情");
                        intent.putExtra("url", jsonObject.getJSONObject("data").getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").getJSONObject(0).getString("mobile_url"));
                        startActivity(intent);
                    }else {
                        showToast(jsonObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void get2(String type){
        RequestParams requestParams = new RequestParams();
        requestParams.put("resource_type",type);
        HttpUtils.post(Constants.APP_IP+"/app.php?c=Pdd&a=genResourceUrl", requestParams, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("dsafsd",responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("dsafsd",responseString);
                try {
                    JSONObject jsonObject=new JSONObject(responseString);
                    if("0".equals(jsonObject.getString("code"))){
                        Intent intent = new Intent(context, WebViewActivity.class);
                        intent.putExtra("title", "详情");
                        intent.putExtra("url", jsonObject.getJSONObject("data").getJSONObject("resource_url_response").getJSONObject("single_url_list").getString("mobile_url"));
                        startActivity(intent);
                    }else {
                        showToast(jsonObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void addListener() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (hasdata) {
                    indexNum++;
                    getTbkListRequst(name);
                } else {
                    showToast("没有更多数据了");
                    refreshLayout.finishLoadMore(1000);
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                indexNum = 1;
                hasdata=true;
                getTbkListRequst(name);
            }
        });
        //点击进入详情
        shopRecyclerAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                PDDBean taobaoGuesChildtBean = taobaoGuesChildtBeans.get(position);
                if (taobaoGuesChildtBean != null) {
                    Intent intent=new Intent(context,PddDetailsActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("goods", taobaoGuesChildtBean);
                    intent.putExtra("goods",bundle);
                    startActivity(intent);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    /**
     * @属性:获取屏幕高度的方法
     * @开发者:陈飞
     * @时间:2018/8/7 14:22
     */
    public long getScollYDistance() {
        int position = linearLayoutManager.findFirstVisibleItemPosition();
        View firstVisiableChildView = linearLayoutManager.findViewByPosition(position);
        if(firstVisiableChildView==null)
            return 0;
        int itemHeight = firstVisiableChildView.getHeight();
        return (position) * itemHeight - firstVisiableChildView.getTop();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void lazyload() { //懒加载，界面开始后刷新
        //开始刷新
        refreshLayout.autoRefresh();
    }
    /**
     * @属性:获取Pdd商品列表
     * @开发者:wmm
     * @时间:2018/11/21 17:05
     */
    private void getTbkListRequst(String search) {
        String time=String.valueOf(System.currentTimeMillis() / 1000);
        RequestParams requestParams = new RequestParams();
        requestParams.put("page",indexNum+"");
        requestParams.put("sort_type",sort_gz);
        requestParams.put("page_size","10");
        requestParams.put("data_type",PddClient.data_type);
        requestParams.put("client_id",PddClient.client_id);
        requestParams.put("timestamp",time);
        requestParams.put("with_coupon","true");
        requestParams.put("type","pdd.ddk.goods.search");
        if(pid.equals("0")){
            requestParams.put("opt_id",pid);
        }else{
            requestParams.put("cat_id", pid);
        }
        Map<String,Object> temp=new HashMap<>();
        temp.put("page",indexNum+"");
        if(pid.equals("0")){
            temp.put("opt_id",pid);
        }else{
            temp.put("cat_id", pid);
        }
        temp.put("sort_type",sort_gz);
        temp.put("page_size","10");
        temp.put("data_type",PddClient.data_type);
        temp.put("type","pdd.ddk.goods.search");
        temp.put("client_id",PddClient.client_id);
        temp.put("timestamp",time);
        temp.put("with_coupon","true");
        String sign=PddClient.getSign(temp);
        requestParams.put("sign",sign);
        HttpUtils.post1(PddClient.serverUrl, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
                if (refreshLayout != null) {
                    if (indexNum == 1) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMore();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if(responseString.contains("error_response")){
                    return;
                }
                if(indexNum==1){
                    taobaoGuesChildtBeans.clear();
                }
                try {
                    JSONObject jsonObject=new JSONObject(responseString);
                    JSONArray array=jsonObject.getJSONObject("goods_search_response").getJSONArray("goods_list");
                    JSONObject tempObj;
                    for(int i=0;i<array.length();i++){
                        tempObj=array.getJSONObject(i);
                        double tem=(Double.valueOf(tempObj.getString("min_group_price"))-Double.valueOf(tempObj.getString("coupon_discount")))*Double.valueOf(df.format(Double.valueOf(tempObj.getString("promotion_rate"))/1000));
                        tempObj.put("commission",df.format(  tem*SPUtils.getIntData(context,"rate",0)/100));
                        taobaoGuesChildtBeans.add(gson.fromJson(tempObj.toString(),PDDBean.class));
                    }
                    shopRecyclerAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @OnClick({R.id.right_icon,R.id.jiage_st,R.id.yongjin_st,R.id.xiaoliang_st})
    public void onViewClicked(View view) { //回到头部
        switch (view.getId()) {
            case R.id.right_icon:
                recyclerView.post(new Runnable() {
                    @Override
                    public void run() {
                        recyclerView.smoothScrollToPosition(0);
                    }
                });
                break;
            case R.id.xiaoliang_st: //销量
                sort_gz="6";
                refreshLayout.autoRefresh();
                selectView(1);
                break;
            case R.id.jiage_st: //价格
                sort_gz = "3";
                refreshLayout.autoRefresh();
                selectView(0);
                break;
            case R.id.yongjin_st: //奖
                sort_gz="14";
                refreshLayout.autoRefresh();
                selectView(2);
                break;
        }
    }
    private void selectView(int position) {
        for (TextView textView : textViews) {
            textView.setTextColor(getResources().getColor(R.color.black));
        }
        textViews[position].setTextColor(getResources().getColor(R.color.red1));
    }

}
